<template>
	<view class="page container">
		<u-form :model="basicForm" :rules="rules" labelPosition="top" ref="form" labelWidth="auto" :labelStyle="{
        fontSize: '14px',
        color: '#B2B2B2',
        lineHight: '20px',
      }">
			<view class="basic-style">
				<u-form-item :label="relBillType=='1'?'冲账借款单据':'冲账付款单单据'" prop="relBillId" required>
					<h-select-borrowbill-input-popup v-if="relBillType=='1'" :disabled="!applicant || formBpm" :checkStatus="2"
						:companyId="applicant" :settleAccounts="0" :proposer="proposer" class="w-100"
						v-model="basicForm.relBillId" placeholder="请选择关联借款申请" border="surround" suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@realChange="relBillData"></h-select-borrowbill-input-popup>
					<selectPayPop
						v-if="relBillType=='2'"
						:teamId="teamId"
						:disabled="!applicant || !teamId || formBpm"
						:applicant="applicant"
						class="w-100"
						v-model="basicForm.relBillId"
						placeholder="请选择付款单单据"
						border="surround"
						suffixIcon="arrow-down-fill"
						:suffixIconStyle="{ color: '#B2B2B2' }"
						@realChange="relBillData"/>
				</u-form-item>
				<template v-if="relBillType=='1'">
					<u-form-item label="借款金额(元)" prop="borrowLoanAmount">
						<u--input disabled placeholder="请输入借款金额" v-model="basicForm.borrowLoanAmount"></u--input>
					</u-form-item>
					<u-form-item label="已还金额(元)" prop="borrowOnloanAmount">
						<u--input disabled placeholder="请输入已还金额" v-model="basicForm.borrowOnloanAmount"></u--input>
					</u-form-item>
				</template>
				<template v-if="relBillType=='2'">
					<u-form-item label="预付款金额(元)" prop="payPayableAmount">
						<u--input disabled placeholder="请输入预付款金额" v-model="basicForm.payPayableAmount"></u--input>
					</u-form-item>
					<u-form-item label="已冲账金额(元)" prop="payOnChargedAmount">
						<u--input disabled placeholder="请输入已冲账金额" v-model="basicForm.payOnChargedAmount"></u--input>
					</u-form-item>
				</template>
				<u-form-item label="本次冲账金额(元)" prop="chargedAmount" required>
					<h-money-input placeholder="请输入本次冲账金额" v-model="basicForm.chargedAmount"
						@input="inputChargedAmount"></h-money-input>
				</u-form-item>
				<u-form-item label="剩余未冲账金额(元)" prop="unChargedAmount">
					<u--input disabled placeholder="请输入剩余未冲账金额" v-model="basicForm.unChargedAmount"></u--input>
				</u-form-item>
			</view>
			<view class="space-x-1 mt-1" style="display: flex">
				<u-button type="primary" text="保存" :loading="loading" @click="onSubmit"></u-button>
				<u-button type="primary" text="关闭" :loading="loading" @click="onClose"></u-button>
			</view>
		</u-form>
	</view>
</template>

<script>
	import Decimal from 'decimal.js'
	import http from '@/utils/request'
	import selectPayPop from '../reimComp/comp/h-select-pay-input-popup.vue'
	export default {
		name: 'ReversePaymentForm',
		components: {selectPayPop},
		props: {
			disabled: {
				type: Boolean,
				default: false,
				required: false,
			},
			index: {
				type: Number,
				default: null,
			},
			teamId: {
				type: String,
				default: null
			},
			applicant: {
				type: String,
				default: null
			},
			relBillType:{
				type: String,
				default: null
			},
			//表单模式：true流程表单 false普通表单
			formBpm: {
				type: Boolean,
				default: false,
				required: false
			},
			childSource: {
				type: [Array,null],
			}
		},
		data() {
			return {
				loading: false,
				// dataSource: [],
				proposer: uni.getStorageSync('userInfo').empId,
				basicForm: {
					relBillId: '',
					borrowLoanAmount: '',
					borrowOnloanAmount: '',
					payOnChargedAmount:'',
					payPayableAmount:'',
					chargedAmount: '',
					unChargedAmount: '',
				},
				rules: {
					relBillId: [{
						required: true,
						message: '请选择关联的冲账单据!',
						trigger: ['change', 'blur']
					}],
					chargedAmount: [{
						required: true,
						trigger: ['change', 'blur'],
						// pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
						pattern: /^(?!0\.00)(?!0$)([1-9]\d*|0)(\.\d{2})?$/,
						message: '请输入正确的金额!',
					}],
					unChargedAmount: [{
						required: true,
						trigger: ['change', 'blur'],
						pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/,
						message: '剩余未冲账金额不正确!',
					}],
				},
			}
		},
		methods: {
			/**
			 * 选择关联借款单申请
			 */
			relBillData(data) {
				let id=this.basicForm.relBillId;
				if(this.relBillType=="1"){//借款单
					http.get("/api/erp/finance/borrow/erpFinanceLoanBill/queryById",{'id':id}).then((res) => {
						if (res.success) {
							let val=res.result;
							let loanAmount=val.amount;//借款金额
							let onloanAmount=Number(val.repaymentAmount)+Number(val.travelReimbursementAmount)+Number(val.expenseReimbursementAmount);//已还金额
							this.$set(this.basicForm,'borrowLoanAmount',loanAmount);
							this.$set(this.basicForm,'borrowOnloanAmount',onloanAmount);
							this.inputChargedAmount(this.basicForm.chargedAmount)
						}
					})
				}else if(this.relBillType=="2"){//付款单
					http.get("/api/erp/finance/payment/erpFinancePaymentSlipFeeDetail/queryBillInfoByBillId",{'billId':id}).then((res) => {
						if (res.success) {
							let resResult=res.result.records[0];
							let payPayableAmount=resResult.currentPaidAmount;//应付金额
							let onChargedAmount=resResult.onChargedAmount;//冲账金额
							this.$set(this.basicForm,'payOnChargedAmount',onChargedAmount);
							this.$set(this.basicForm,'payPayableAmount',payPayableAmount);
							this.inputChargedAmount(this.basicForm.chargedAmount)
						}
					})
				}
			},
			inputChargedAmount(data) {
				let value = Number(data) || 0
				let unChargedAmount=0;
				if(this.relBillType=="1"){//借款单
					let borrowLoanAmount=Number(this.basicForm.borrowLoanAmount);
					let borrowOnloanAmount=Number(this.basicForm.borrowOnloanAmount);
					unChargedAmount=(borrowLoanAmount.toFixed(2)-borrowOnloanAmount.toFixed(2)-value.toFixed(2)).toFixed(2);
				}else if(this.relBillType=="2"){//付款单
					let payPayableAmount=Number(this.basicForm.payPayableAmount);
					let payOnChargedAmount=Number(this.basicForm.payOnChargedAmount);
					unChargedAmount=(payPayableAmount.toFixed(2)-payOnChargedAmount.toFixed(2)-value.toFixed(2)).toFixed(2);
				}
				if(!data||!this.basicForm.relBillId){
					return
				}
				this.$set(this.basicForm,'unChargedAmount',unChargedAmount);
			},
			reset() {
				this.$refs.form.resetFields()
			},
			async onSubmit() {
				await this.$refs.form.validate()
				if(this.childSource.length>0){
					let validRes=this.childSource.filter(item=>item.relBillId==this.basicForm.relBillId && item.id!=this.basicForm.id);
					if(validRes.length>0){
						this.$u.toast('该冲账单据已经存在，请勿重复选择！')
						return false;
					}
				}
				if (!this.index) {
					this.$emit('submit', [{
							id: parseInt(Math.random() * 1000000000000),
							...this.basicForm,
						},
						this.index,
					])
				} else {
					this.$emit('submit', [this.basicForm, this.index])
				}
				this.reset()
			},
			onClose() {
				this.$emit('close')
				this.reset()
			},
		}
	}
</script>

<style scoped>
	@import url('@/assets/inputStyle.scss');

	.page.container {
		padding: 20px;
	}

	.basic-style {
		margin: 0;
		max-height: 80vh;
		overflow-y: auto;
	}

	.u-form-item {
		padding: 0px 8px;
	}
</style>